package com.uzai.console.service.alipaydetail.impl;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.entity.WechatUser;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.constant.CommonConstant;
import com.uzai.console.dto.alipaydetail.AlipayDetailQuery;
import com.uzai.console.dto.alipaymchbatch.AlipayMchBatchQuery;
import com.uzai.console.entity.AlipayDetail;
import com.uzai.console.entity.AlipayMchBatch;
import com.uzai.console.entity.UserTakeBal;
import com.uzai.console.enums.AlipayStatusEnum;
import com.uzai.console.mapper.AlipayDetailMapper;
import com.uzai.console.mapper.AlipayMchBatchMapper;
import com.uzai.console.service.alipaydetail.AlipayDetailService;
import com.uzai.console.service.alipaydetail.AlipayTradeSyncService;
import com.uzai.console.service.alipaymch.AlipayMchBatchPayService;
import com.uzai.console.service.ratelimit.RatelimitService;
import com.uzai.console.service.takebal.UserTakeBalService;
import com.uzai.console.service.takebal.UserTakeBalSyncService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author liuqi
 * @date 2021年08月25日 20:17
 */
@Service
public class AlipayTradeSyncServiceImpl implements AlipayTradeSyncService {

    Logger logger = LoggerFactory.getLogger(AlipayTradeSyncServiceImpl.class);

    @Autowired
    private AlipayDetailMapper alipayDetailMapper;
    @Autowired
    private AlipayDetailService alipayDetailService;
    @Autowired
    private RatelimitService ratelimitService;
    @Autowired
    private AlipayMchBatchMapper alipayMchBatchMapper;
    @Autowired
    private AlipayMchBatchPayService alipayMchBatchPayService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 支付宝线下交易查询
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param
     * @return null
     */
    @Async("taskExecutor")
    public void alipayTradeQuery(){
        //限流key
        String taskLimitKet = "-alipayTradeQuery-taskLimitKey-";
        Object object = redisTemplate.opsForValue().get(taskLimitKet);
        if(object != null){
            return;
        }
        //保存限流key
        redisTemplate.opsForValue().set(taskLimitKet, taskLimitKet, 30, TimeUnit.MINUTES);

        logger.info("-----调用支付宝在线查询支付结果线程--xxlJob start--");

        try{
            Integer now = DateUtil.getNowTime();
            AlipayDetailQuery alipayDetailQuery = new AlipayDetailQuery();
            alipayDetailQuery.setStatus(AlipayStatusEnum.WAIT_BUYER_PAY.getId().intValue()); //等待付款

            //查询所有的支付宝支付记录
            Page<AlipayDetail> page = new Page<>();
            page.setCurrent(1);//只查第一页
            page.setSize(10); //每页查询10个
            page.addOrder(OrderItem.asc("id"));//默认id升序
            Long idStart = 0L;
            List<AlipayDetail> alipayDetailList = alipayDetailMapper.findByListForXxlJob(page, alipayDetailQuery);
            while (alipayDetailList != null && alipayDetailList.size() > 0){
                for (AlipayDetail alipayDetail : alipayDetailList){
                    try{
                        if(alipayDetail.getId().longValue() > idStart.longValue()){
                            idStart = alipayDetail.getId();
                        }
                        //限流判断
                        boolean inRateLimit = ratelimitService.inRateLimit("Alipay-" + alipayDetail.getTradeno(),1,10);
                        if (!inRateLimit){
                            //logger.info("--inRateLimit false. tradeno={}",alipayDetail.getTradeno());
                            continue;
                        }
                        alipayDetailService.alipayTradeQuery(alipayDetail.getTradeno());
                    }catch (Exception e){
                        logger.error("--调用支付宝在线查询失败--{}", e);
                    }
                }

                alipayDetailQuery.setIdStart(idStart);
                alipayDetailList = alipayDetailMapper.findByListForXxlJob(page, alipayDetailQuery);
            }
        }catch (Exception e){
            logger.info(e.getMessage());
        }finally {
            //删除限流key
            redisTemplate.delete(taskLimitKet);
        }

    }


    /**
     * 个人支付宝批量转账交易查询
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param
     * @return null
     */
    @Async("taskExecutor")
    public void alipayMchBatchQuery(){

        //限流key
        String taskLimitKet = "-alipayMchBatchQuery-taskLimitKey-";
        Object object = redisTemplate.opsForValue().get(taskLimitKet);
        if(object != null){
            return;
        }
        //保存限流key
        redisTemplate.opsForValue().set(taskLimitKet, taskLimitKet, 30, TimeUnit.MINUTES);

        logger.info("-----调用提现个人支付宝批量转账查询支付结果线程--xxlJob start--");

        try{
            Integer now = DateUtil.getNowTime();
            AlipayMchBatchQuery alipayMchBatchQuery = new AlipayMchBatchQuery();
            alipayMchBatchQuery.setStatus(AlipayStatusEnum.WAIT_BUYER_PAY.getId().intValue()); //等待付款

            //查询所有的支付宝支付记录
            Page<AlipayMchBatch> page = new Page<>();
            page.setCurrent(1);//只查第一页
            page.setSize(10); //每页查询10个
            page.addOrder(OrderItem.asc("id"));//默认id升序
            Long idStart = 0L;
            List<AlipayMchBatch> alipayMchBatchList = alipayMchBatchMapper.findByList(page, alipayMchBatchQuery);
            while (alipayMchBatchList != null && alipayMchBatchList.size() > 0){
                for (AlipayMchBatch alipayMchBatch : alipayMchBatchList){
                    try{
                        if(alipayMchBatch.getId().longValue() > idStart.longValue()){
                            idStart = alipayMchBatch.getId();
                        }
                        //限流判断
                        boolean inRateLimit = ratelimitService.inRateLimit("AlipayMchBatch-" + alipayMchBatch.getId(),1,10);
                        if (!inRateLimit){
                            //logger.info("--inRateLimit false. tradeno={}",alipayDetail.getTradeno());
                            continue;
                        }
                        alipayMchBatchPayService.alipayMchBatchQuery(alipayMchBatch.getId());
                    }catch (Exception e){
                        logger.error("--调用提现个人支付宝批量转账查询失败-{}", e);
                    }
                }

                alipayMchBatchQuery.setIdStart(idStart);
                alipayMchBatchList = alipayMchBatchMapper.findByList(page, alipayMchBatchQuery);
            }

        }catch (Exception e){
            logger.info(e.getMessage());
        }finally {
            //删除限流key
            redisTemplate.delete(taskLimitKet);
        }
    }

}
